import { memo, useCallback, useState } from 'react'
import Notification from './notification'
import { sendMB } from '../../../../infrastructure/event-tracking'
import getMeta from '../../../../utils/meta'
import customLocalStorage from '../../../../infrastructure/local-storage'

const STORAGE_KEY = 'has_dismissed_writefull_promo_banner'

const eventSegmentation = {
  location: 'dashboard-banner',
  page: '/project',
  name: 'writefull',
}

const isChromium = () =>
  (window.navigator as any).userAgentData?.brands?.some(
    (item: { brand: string }) => item.brand === 'Chromium'
  )

function WritefullPromoBanner() {
  const [show, setShow] = useState(() => {
    const show =
      getMeta('ol-showWritefullPromoBanner') &&
      !customLocalStorage.getItem(STORAGE_KEY)

    if (show) {
      sendMB('promo-prompt', eventSegmentation)
    }

    return show
  })

  const handleOpenLink = useCallback(() => {
    sendMB('promo-click', eventSegmentation)
  }, [])

  const handleClose = useCallback(() => {
    customLocalStorage.setItem(STORAGE_KEY, new Date())
    setShow(false)
    sendMB('promo-dismiss', eventSegmentation)
  }, [])

  if (!show) {
    return null
  }

  if (!isChromium()) {
    return null
  }

  return (
    <Notification
      bsStyle="info"
      onDismiss={handleClose}
      className="centered-alert"
    >
      <Notification.Body>
        <span>
          Get <b>10% off</b> Writefull premium—AI-based language feedback and
          TeXGPT to help you write great papers faster. Use code:{' '}
          <b>OVERLEAF10</b>
        </span>
      </Notification.Body>
      <Notification.Action>
        <a
          className="pull-right btn btn-info btn-sm"
          href="https://my.writefull.com/overleaf-invite?code=OVERLEAF10"
          target="_blank"
          rel="noreferrer"
          onClick={handleOpenLink}
        >
          <img
            alt="Writefull Logo"
            src=""
            height={16}
            width={16}
            style={{ marginRight: 4 }}
          />
          <span>Get Writefull for Overleaf</span>
        </a>
      </Notification.Action>
    </Notification>
  )
}

export default memo(WritefullPromoBanner)
